﻿using System.Collections.Generic;
using System.Linq;

namespace Sidvall.Security
{
    public class EntityItemCollection : System.Collections.ObjectModel.KeyedCollection<string, EntityItem>
    {
        #region Public Members

        #region Add

        public void Add(string entityName, int readAccessLevel, int writeAccessLevel)
        {
            var item = new EntityItem()
            {
                EntityName = entityName,
                ReadAccessLevel = readAccessLevel,
                WriteAccessLevel = writeAccessLevel,
            };
            Add(item);
        }

        #endregion
        #region AddRange

        public void AddRange(int readAccessLevel, int writeAccessLevel, params string[] entityNames)
        {
            AddRange(readAccessLevel, writeAccessLevel, entityNames.AsEnumerable());
        }
        public void AddRange(int readAccessLevel, int writeAccessLevel, IEnumerable<string> entityNames)
        {
            if (entityNames == null)
                return;
            foreach (var entityName in entityNames)
                Add(entityName, readAccessLevel, writeAccessLevel);
        }

        #endregion
        #region Merge

        public EntityItem Merge(string entityName, int readAccessLevel, int writeAccessLevel)
        {
            var item = FindItem(entityName);
            if (item != null)
            {
                item.ReadAccessLevel = readAccessLevel;
                item.WriteAccessLevel = writeAccessLevel;
            }
            else
            {
                item = new EntityItem()
                {
                    EntityName = entityName,
                    ReadAccessLevel = readAccessLevel,
                    WriteAccessLevel = writeAccessLevel,
                };
                Add(item);
            }
            return item;
        }

        #endregion
        #region FindItem

        public EntityItem FindItem(string entityName)
        {
            if (!string.IsNullOrWhiteSpace(entityName))
            {
                if (Contains(entityName))
                    return this[entityName];
            }
            return null;
        }

        #endregion
        #region GetKeyForItem

        protected override string GetKeyForItem(EntityItem item)
        {
            if (item == null)
                throw new System.ArgumentNullException(nameof(item));
            return item.EntityName;
        }

        #endregion

        #endregion
    }
}
